<template>
  <view class="keyboard-aware-input">
    <!-- 使用uview-plus的输入框组件 -->
    <u-input
      v-model="inputValue"
      :placeholder="placeholder"
      @focus="handleFocus"
      @blur="handleBlur"
      ref="inputRef"
      :class="inputClass"
    ></u-input>
  </view>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';

// 接收父组件传递的参数
const props = defineProps({
  placeholder: {
    type: String,
    default: '请输入内容'
  },
  modelValue: {
    type: String,
    default: ''
  },
  inputClass: {
    type: String,
    default: ''
  },
  // 可自定义键盘高度预估值，默认200px
  keyboardHeight: {
    type: Number,
    default: 200
  }
});

// 向父组件 emits 事件
const emit = defineEmits(['update:modelValue', 'focus', 'blur']);

// 输入框绑定的值
const inputValue = ref(props.modelValue);
// 输入框引用
const inputRef = ref(null);
// 原始滚动位置
let originalScrollTop = 0;
// 是否已经滚动
let hasScrolled = false;

// 监听输入框值变化，同步到父组件
watch(inputValue, (newVal) => {
  emit('update:modelValue', newVal);
});

// 获取当前页面滚动位置
const getCurrentScrollTop = () => {
  return new Promise(resolve => {
    uni.createSelectorQuery().selectViewport().boundingClientRect(rect => {
      resolve(rect.scrollTop || 0);
    }).exec();
  });
};

// 处理输入框聚焦事件
const handleFocus = async (e) => {
  emit('focus', e);
  
  // 保存原始滚动位置
  originalScrollTop = await getCurrentScrollTop();
  hasScrolled = false;
  
  // 等待输入框渲染和键盘弹出
  // 增加延迟时间确保键盘已经弹出
  setTimeout(async () => {
    if (!inputRef.value) return;
    
    // 获取输入框位置信息
    const rect = await new Promise(resolve => {
      inputRef.value.$el.getBoundingClientRect(rect => {
        resolve(rect);
      });
    });
    
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync();
    const windowHeight = systemInfo.windowHeight;
    
    // 计算输入框底部到屏幕底部的距离
    const bottomDistance = windowHeight - rect.bottom;
    
    // 如果输入框会被键盘遮挡，则上推页面
    if (bottomDistance < props.keyboardHeight) {
      // 计算需要滚动的距离
      const needScroll = rect.bottom - (windowHeight - props.keyboardHeight) + 20; // 加20px安全距离
      const targetScrollTop = originalScrollTop + needScroll;
      
      // 执行滚动
      uni.pageScrollTo({
        scrollTop: targetScrollTop,
        duration: 300,
        success: () => {
          hasScrolled = true;
        }
      });
    }
  }, 300); // 增加延迟确保键盘已弹出
};

// 处理输入框失焦事件
const handleBlur = (e) => {
  emit('blur', e);
  
  // 失焦后恢复原始滚动位置（如果之前滚动过）
  if (hasScrolled) {
    uni.pageScrollTo({
      scrollTop: originalScrollTop,
      duration: 300
    });
    hasScrolled = false;
  }
};

onUnmounted(() => {
  // 组件卸载时确保页面回到原始位置
  if (hasScrolled) {
    uni.pageScrollTo({
      scrollTop: originalScrollTop,
      duration: 0
    });
  }
});
</script>

<style scoped>
.keyboard-aware-input {
  /* 可以根据需要添加样式 */
}
</style>
